package me.helllp.bootman.common.utils;

import java.util.List;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import me.helllp.bootman.common.base.BaseReturn;
import me.helllp.bootman.common.base.ErrorCodeEnum;

public final class ResultUtil {
	private static BaseReturn createReturn(int code,String msg,Object obj){
		BaseReturn ret = new BaseReturn();

		ret.setCode(code);
		ret.setMessage(msg);	
		
		if(obj != null){
			ret.setData(obj);
			ret.setType(obj.getClass().getName());			
		}
		
		return ret;		
	}
	
	/**
	 * 构造标准正确的返回结构
	 * 
	 * @param obj
	 * @return
	 */
	public static BaseReturn genSuccessResult(Object obj){
		return createReturn(ErrorCodeEnum.SYS_NORMAL.getCode(),"",obj);
	}
	
	public static BaseReturn genResultByEnums(ErrorCodeEnum e, Object obj){
		return createReturn(e.getCode(), e.getMsg(), obj);
	}
	
    /**
     * 返回规则校验错误
     * 
     * @param checkRusult
     * @return
     */
    public static BaseReturn genCheckResult(BindingResult checkRusult) {
		if (checkRusult.hasErrors()) {
			List<ObjectError> list = checkRusult.getAllErrors();

			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < list.size(); i++) {
				if (i > 0) {
					sb.append(",");
				}
				sb.append(list.get(i).getDefaultMessage());
			}

			BaseReturn ret = new BaseReturn();
			ret.setCode(ErrorCodeEnum.SYS_INPUT.getCode());
			ret.setData("");
			ret.setMessage(sb.toString());
			ret.setType("");
			
			return ret;
		}else{
			return genSuccessResult("");
		}
    }
}
